package com.itheima.reggie.aop;


import com.itheima.reggie.common.BaseThreadLocal;
import com.itheima.reggie.domain.CommonEntity;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/*@Slf4j
@Component
@Aspect*/
public class CommonAdvice {
    //切入点
    @Pointcut("execution(* com.itheima.reggie.controller.*Controller.save*(..))"
              +" || "+
              "execution(* com.itheima.reggie.controller.*Controller.update*(..))")
    public void pt(){}

    @Around("pt()")//切面
    //增强的功能 ，对四个字段的值进行自动填充！！
    public Object modifyColumn(ProceedingJoinPoint pjp){
        Object proceed = null;
        Object[] args = pjp.getArgs(); //获取被切函数 参数
        CommonEntity obj = (CommonEntity) args[0];
        String methodName = pjp.getSignature().getName();//pjp.getSignature()获取切名
        Long id = BaseThreadLocal.get();//从ThreadLocal中获取id
        if (methodName.startsWith("save")){
            obj.setCreateTime(LocalDateTime.now());
            obj.setCreateUser(id);
        }
        obj.setUpdateTime(LocalDateTime.now());
        obj.setUpdateUser(id);
        try {
            proceed = pjp.proceed(args);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return proceed;
    }
}
